package com.lws.framework.module.idcode.controller;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.lws.framework.module.idcode.service.IDCodeService;

@Controller
@RequestMapping("/idCode.do")
public class IDCodeController {

    @Autowired
    private IDCodeService idCodeService;

    @ResponseBody
    @RequestMapping(params = "method=randomIDCode")
    public void randomIDCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String randomIDCode = idCodeService.randomCode();
        BufferedImage image = idCodeService.createImage(randomIDCode);

        // 将四位数字的验证码保存到Session中         
        HttpSession session = request.getSession();
        session.setAttribute("serverIDCode", randomIDCode.toString());

        // 禁止图像缓存         
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");

        // 将图像输出到Servlet输出流中         
        OutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpeg", out);
        out.close();
    }

    @ResponseBody
    @RequestMapping(params = "method=checkIDCode")
    public String checkIDCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String clientIDCode = request.getParameter("clientIDCode");
        String serverIDCode = (String) request.getSession().getAttribute("serverIDCode");
        if (clientIDCode == null || serverIDCode == null)
            return "fail";

        if (serverIDCode.equalsIgnoreCase(clientIDCode)) {
            return "success";
        } else {
            return "fail";
        }
    }
}
